<template>
  <div class="weather-display" v-if="weatherData">
    <span class="weather-emoji">{{ getWeatherEmoji(weatherData.data.type) }}</span>
    <span class="temp"> {{ weatherData.data.low }}{{ weatherData.data.high }}</span>
    <span class="weather-text">{{ weatherData.data.type }}</span>
  </div>
  <div v-else class="weather-display loading">
    <span class="weather-emoji">⏳</span>
    <span class="weather-text">加载中...</span>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'WeatherDisplay',
  data()
  {
    return {
      weatherData: null // 存储天气数据
    }
  },
  created()
  {
    this.fetchWeather()
    console.log('WeatherDisplay component initialized')
  },
  methods: {
    // 获取天气数据
    async fetchWeather()
    {
      try
      {
        const response = await axios.get('https://api.vvhan.com/api/weather')
        if (response.data.success)
        {
          this.weatherData = response.data
          console.log('Weather fetched:', this.weatherData)
        }
        else
        
          this.$message.error(`获取天气失败: ${response.data.message || '未知错误'}`)
      }
      catch (error)
      {
        this.$message.error('网络错误，请稍后重试')
        console.error('Fetch weather error:', error)
      }
    },

    // 根据天气类型返回对应的 Emoji
    getWeatherEmoji(weatherType)
    {
      const weatherEmojis = {
        晴: '☀️',
        多云: '☁️',
        阴: '🌫️',
        小雨: '🌧️',
        中雨: '🌧️',
        大雨: '⛈️',
        雪: '❄️',
        雨夹雪: '🌨️',
        雾: '🌫️',
        沙尘暴: '🌪️'
      }
      return weatherEmojis[weatherType] || '🌡️' // 默认使用温度计图标
    }
  }
}
</script>

<style scoped>
.weather-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 160px;
  height: 42px;
  padding: 0 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 21px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-size: 40px;
  color: #2f2f2f;
}

.weather-emoji {
  font-size: 28px;
  margin-right: 0px;
}

.temp {
  font-size: 14px;
  color: #91929b;
}

.weather-text {
  font-size: 28px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.loading {
  background-color: #f0f0f0;
  color: #666;
}

.loading .weather-emoji {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
